package com.cloudkinto.controller.order.returns;


import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.dto.order.returns.OrderReturnPageDto;
import com.cloudkinto.vo.order.returns.*;
import com.cloudkinto.vo.order.returns.importVo.OrderReturnImportRes;
import com.cloudkinto.vo.order.returns.print.PrintReq;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.cloudkinto.service.order.returns.OrderReturnService;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.cloudkinto.base.BaseController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 * @author hua
 * @since 2024-11-19
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "退件OMS模块")
@RequestMapping("/api/admin/oms/OrderReturn")
public class OrderReturnOmsController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(OrderReturnWmsController.class);

    private final OrderReturnService service;

    @UserSessionRequired
    @PostMapping
    @ApiOperation(value = "退件新增", notes = "退件新增")
    public SingleResult add(@RequestBody @Validated OrderReturnAddReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("新增成功", service.addReturn(req, userId, getCompanyId()));
    }


    @UserSessionRequired
    @PutMapping
    @ApiOperation(value = "修改", notes = "修改")
    public SingleResult update(@RequestBody @Validated OrderReturnUpdateReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功",service.update(req, userId, getCompanyId(), "oms"));
    }

    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = OrDetailRes.class))
    public SingleResult detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功",service.detail(id, getCompanyId(), "oms"));
    }

    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit(getCurrentUserId(), getCompanyId(), getTenantId(), "oms");
    }


    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "returnType", value = "退件类型 1平台退件 2买家退件 3服务商退件"),
            @ApiImplicitParam(name = "storageIds", value = "仓库", type = "arr"),
            @ApiImplicitParam(name = "dateColumn", value = "筛选日期类型 create_time submit_time 等等"),
            @ApiImplicitParam(name = "beginTime", value = "开始时间"),
            @ApiImplicitParam(name = "endTime", value = "结束时间"),
            @ApiImplicitParam(name = "selectColumn", value = "查询类型 sku, fn_sku, track_no 等等"),
            @ApiImplicitParam(name = "selectValue", value = "查询值"),
            @ApiImplicitParam(name = "selectColumn1", value = "查询类型1"),
            @ApiImplicitParam(name = "selectValue1", value = "查询值1"),
            @ApiImplicitParam(name = "status", value = "状态"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")
    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = OrderReturnPageDto.class))
    public PageResult listPage(HttpServletRequest request){
        Map<String, Object> map = this.getMap(request);
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        map.put("current", current);
        map.put("pageSize", size);
        return service.getListPage(map);
    }


    public Map<String, Object> getMap(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String returnType = request.getParameter("returnType");
        String[] storageIds = request.getParameterValues("storageIds");
        String dateColumn = request.getParameter("dateColumn");
        String beginTime = request.getParameter("beginTime");
        String endTime = request.getParameter("endTime");
        String selectColumn = request.getParameter("selectColumn");
        String selectValue = request.getParameter("selectValue");
        String selectColumn1 = request.getParameter("selectColumn1");
        String selectValue1 = request.getParameter("selectValue1");
        String status = request.getParameter("status");

        map.put("companyId", getCompanyId());
        map.put("returnType", returnType);
        if (storageIds != null) {
            map.put("storageIds", Arrays.asList(storageIds));
        }
        map.put("dateColumn", dateColumn);
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("selectColumn", selectColumn);
        map.put("selectValue", selectValue);
        map.put("selectColumn1", selectColumn1);
        map.put("selectValue1", selectValue1);
        map.put("status", status);
        map.put("tenantId", getTenantId());

        return map;
    }


    @UserSessionRequired
    @PutMapping("/submit")
    @ApiOperation(value = "提交退件单", notes = "提交退件单")
    public SingleResult submit(@RequestBody @Validated OrUtilReq req) {
        Long userId = getCurrentUserId();
        service.submit(req, userId, getCompanyId());
        return SingleResult.success();
    }


    @UserSessionRequired
    @PutMapping("/cancel")
    @ApiOperation(value = "取消退件单", notes = "取消退件单")
    public SingleResult cancel(@RequestBody @Validated OrUtilReq req) {
        Long userId = getCurrentUserId();
        service.cancel(req, userId, getCompanyId());
        return SingleResult.success();
    }

    @UserSessionRequired
    @GetMapping("/packageList")
    @ApiOperation(value = "添加包裹-获取包裹详情", notes = "根据id查看详情")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = OrDetailRes.class))
    public SingleResult packageList(Long id) {
        return SingleResult.success("查询成功",service.packageList(id));
    }

    @UserSessionRequired
    @GetMapping("/statusStatistics")
    @ApiOperation(value = "状态数量统计", notes = "状态数量统计")
    @ApiImplicitParams({@ApiImplicitParam(name = "returnType", value = "退件类型 1平台退件 2买家退件 3服务商退件"),
            @ApiImplicitParam(name = "storageIds", value = "仓库", type = "arr"),
            @ApiImplicitParam(name = "dateColumn", value = "筛选日期类型 create_time submit_time 等等"),
            @ApiImplicitParam(name = "beginTime", value = "开始时间"),
            @ApiImplicitParam(name = "endTime", value = "结束时间"),
            @ApiImplicitParam(name = "selectColumn", value = "查询类型 sku, fn_sku, track_no 等等"),
            @ApiImplicitParam(name = "selectValue", value = "查询值"),
            @ApiImplicitParam(name = "status", value = "状态"),
    })
    public SingleResult statusStatistics(HttpServletRequest request) {
        Map<String, Object> map = this.getMap(request);
        return SingleResult.success(service.statusStatistics(map));
    }


    @UserSessionRequired
    @PostMapping("/updatePackage")
    @ApiOperation(value = "添加包裹", notes = "添加包裹")
    public SingleResult updatePackage(@RequestBody @Validated OrderReturnPUpdateReq req) {
        Long userId = getCurrentUserId();
        service.updatePackage(req,userId);
        return SingleResult.success();
    }

    @UserSessionRequired
    @PostMapping("/updateExpectedDate")
    @ApiOperation(value = "更新预计到达时间", notes = "添加包裹")
    public SingleResult updateExpectedDate(@RequestBody @Validated UpdateExpectedDateReq req) {
        Long userId = getCurrentUserId();
        service.updateExpectedDate(req,userId);
        return SingleResult.success();
    }

    @UserSessionRequired
    @PostMapping("/importOrderReturn")
    @ApiOperation(value = "导入退件单")
    @ApiImplicitParams({@ApiImplicitParam(name = "warehouseId", value = "仓库id", required = true),
    })
    @ApiResponses(@ApiResponse(code = 200, message = "", response = OrderReturnImportRes.class))
    public SingleResult importOrderReturn(MultipartFile file, HttpServletRequest request) {
        String warehouseId = request.getParameter("warehouseId");
        OrderReturnImportRes res = service.importOrderReturn(file, getCurrentUserId(), StringUtils.isBlank(warehouseId) ? null : Long.parseLong(warehouseId), getCompanyId());
        return SingleResult.success(res);
    }


    @UserSessionRequired
    @PostMapping("/printBarCodePdf")
    @ApiOperation(value = "打印SKU", notes = "打印SKU")
    public void printBarCodePdf(@RequestBody @Validated PrintReq req, HttpServletResponse response)  {
        service.printBarCodePdf(req, response);
    }


    @UserSessionRequired
    @GetMapping("/exportOrderReturn")
    @ApiOperation(value = "导出退件列表", notes = "")
    @ApiImplicitParams({@ApiImplicitParam(name = "returnType", value = "退件类型 1平台退件 2买家退件 3服务商退件"),
            @ApiImplicitParam(name = "storageIds", value = "仓库", type = "arr"),
            @ApiImplicitParam(name = "dateColumn", value = "筛选日期类型 create_time submit_time 等等"),
            @ApiImplicitParam(name = "beginTime", value = "开始时间"),
            @ApiImplicitParam(name = "endTime", value = "结束时间"),
            @ApiImplicitParam(name = "selectColumn", value = "查询类型 sku, fn_sku, track_no 等等"),
            @ApiImplicitParam(name = "selectValue", value = "查询值"),
            @ApiImplicitParam(name = "selectColumn1", value = "查询类型1"),
            @ApiImplicitParam(name = "selectValue1", value = "查询值1"),
            @ApiImplicitParam(name = "status", value = "状态"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")
    })
    public void exportOrderReturn(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        String ids = request.getParameter("ids");
        if (ids != null) {
            map.put("ids", Arrays.asList(ids.split(",")));
        }
        else {
            map = this.getMap(request);
        }
        service.exportOrderReturn(map, response);
    }


}

